﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Button = System.Windows.Controls.Button;

namespace weighing
{
    /// <summary>
    /// CarNumberInput.xaml 的交互逻辑
    /// </summary>
    public partial class CarNumberInput : System.Windows.Controls.UserControl
    {
        #region var
        private string currProvince = string.Empty;//省份
        private string currLate = String.Empty;//字母部份
        private string currOther = String.Empty;//其它部分

        #endregion

        public Action<string>? Complated { get; set; }
        /// <summary>
        /// 默认传入的车牌号，修改时可以用到
        /// </summary>
        public string CarNumber { get; set; } = "";

        public CarNumberInput()
        {
            InitializeComponent();
        }

        /**
         * 
         * 23个省：辽宁省（辽）、吉林省（吉）、黑龙江省（黑）、河北省（冀）、山西省（晋）、
         * 江苏省（苏）、浙江省（浙）、安徽省（皖）、福建省（闽）、江西省（赣）、山东省（鲁）、
         * 河南省（豫）、湖北省（鄂）、湖南省（湘）、
         * 广东省（粤）、海南省（琼）、四川省（川）、贵州省（贵）、云南省（云）、陕西省（陕）、
         * 甘肃省（甘）、青海省（青），台湾待定。
         * 
         * 五个自治区：宁夏回族自治区（宁）、疆维吾尔自治区（新）、藏自治区（藏）、西壮族自治区（桂）、内蒙古自治区（蒙）。
         * 
         * 两个特别行政区：粤Z为港澳进入内地车辆。
         * 
         * 四个直辖市：北京市（京）、天津市（津）、上海市（沪）、重庆市（渝）。
         * 
       
            private readonly string[] provices = new string[] {
             "云","贵","川", "桂","京","津", "沪","渝","粤",
             "宁","新","藏", "蒙","青","甘", "琼","陕","湘",
             "鄂","豫","苏", "浙","皖","闽", "赣","鲁","晋",
             "冀","黑","吉","辽"
            };
        */
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            this.resultTb.Focus();
        }

        public void SetCarnumber(string carnumber)
        {
            CarNumber = carnumber.Trim();
            if (!CarNumber.IsNullOrEmpty())
            {
                //resultTb.Text = CarNumber;
                currProvince = CarNumber.Substring(0, 1);
                currLate = CarNumber.Substring(1, 1);
                currOther = CarNumber.Substring(2, CarNumber.Length - 2);
                BuildNumber();
            }
        }

        private void BuildNumber()
        {
            string res = currProvince + currLate + currOther;
            this.resultTb.Text = res;
        }

        private void ProviceBtn_click(object sender, RoutedEventArgs e)
        {
            Button? btn = sender as Button;
            currProvince = btn?.Content?.ToString() ?? "";
            BuildNumber();
        }

        private void LaterBtn_click(object sender, RoutedEventArgs e)
        {
            Button? btn = sender as Button;
            var content = btn?.Content?.ToString() ?? "";
            Handle(content, false);
        }

    
        private void NumberBtn_click(object sender, RoutedEventArgs e)
        {
            Button? btn = sender as Button;
            var content = btn?.Content?.ToString() ?? "";
            Handle(content, true);
        }

        private void DelBtn_Click(object sender, RoutedEventArgs e)
        {
            Delete();
        }

        private void OKbtn_Click(object sender, RoutedEventArgs e)
        {
            Ok();
        }

        private void ResultTb_TextChanged(object sender, TextChangedEventArgs e)
        {
            string num = this.resultTb.Text.Trim();
            if (num.IsNullOrEmpty() || MyHelper.RegexHelper.IsVehicleNumber(num))
            {
                this.resultTb.BorderBrush = new SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#787878"));
            }
            else
            {
                this.resultTb.BorderBrush = new SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#dd3320"));
            }
        }

        private void UserControl_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            this.currProvince = "";
            this.currLate = "";
            this.currOther = "";
            this.resultTb.Text = "";
        }

        private void ButtonClose_Click(object sender, RoutedEventArgs e)
        {
            this.resultTb.Text = string.Empty;
            string num = this.resultTb.Text.Trim();
            Complated?.Invoke(num);
        }

        private void UserControl_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key >= Key.A && e.Key <= Key.Z && e.Key != Key.I)
            {
                var content = e.Key.ToString();
                Handle(content);
            }
            else if ((e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || (e.Key >= Key.D0 && e.Key <= Key.D9))
            {
                var content = e.Key.ToString().Replace("NumPad","").Replace("D","");
                Handle(content, true);
            }
            else if (e.Key == Key.Back)
            {
                Delete();
            }
            else if (e.Key == Key.Enter)
            {
                Ok();
            }
            else
            {
                Debug.WriteLine(" orther key not do nothig");
            }


        }
        private void Handle(string content, bool isnumber = false)
        {
           if (isnumber == false)
            {
                if (currLate.IsNullOrEmpty())
                {
                    currLate = content;
                }
                else
                {
                    if (currOther.Length >= 6)
                    {
                        string msg = "已超出限定长度";
                        CommonFunction.AlertInfo(msg);
                        return;
                    }
                    currOther += content;
                }
                BuildNumber();
            }
            else
            {
                if (currOther.Length >= 6)
                {
                    string msg = "已超出限定长度";
                    CommonFunction.AlertInfo(msg);
                    return;
                }
                currOther += content;
                BuildNumber();
            }
        }

        private void Delete()
        {
            if (currOther.Length > 0)
            {
                currOther = currOther.Substring(0, currOther.Length - 1);
            }
            else if (currLate.Length > 0)
            {
                currLate = currLate.Substring(0, currLate.Length - 1);
            }
            else
            {
                if (currProvince.Length > 0)
                {
                    currProvince = currProvince.Substring(0, currProvince.Length - 1);
                }
            }
            BuildNumber();
        }

        private void Ok()
        {
            string num = this.resultTb.Text.Trim();
            if (MyHelper.RegexHelper.IsVehicleNumber(num))
            {
                Complated?.Invoke(num);
            }
            else
            {
                CommonFunction.AlertInfo("车牌号输入错误。");
                this.resultTb.Focus();
            }
        }

    }
}
